/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.uaa.controller;

import com.lvyh.lightframe.cloud.common.model.Result;
import com.lvyh.lightframe.cloud.uaa.service.ValidateCodeService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 验证码管理
 */
@Controller
public class ValidateCodeController {
    @Autowired
    private ValidateCodeService validateCodeService;

    /**
     * 创建验证码
     */
    @GetMapping("validate-code/{deviceId}")
    public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
        Assert.notNull(deviceId, "机器码不能为空");
        CaptchaUtil.setHeader(response);

        Captcha captcha = new SpecCaptcha(100, 35, 4); // 三个参数分别为宽、高、位数
        captcha.setCharType(Captcha.TYPE_DEFAULT); // 设置类型：字母数字混合

        validateCodeService.saveImageCode(deviceId, captcha.text().toLowerCase()); // 保存验证码
        captcha.out(response.getOutputStream()); // 输出图片流
    }

    /**
     * 发送手机验证码
     */
    @ResponseBody
    @GetMapping("/validate-sms-code/{mobile}")
    public Result createCode(@PathVariable String mobile) {
        Assert.notNull(mobile, "手机号不能为空");
        return validateCodeService.sendSmsCode(mobile);
    }
}
